﻿#define _CRT_SECURE_NO_WARNINGS 1

#include"SList.h";

//void SLTPrint(SNode* phead)
//{
//	SNode* pcur = phead;
//	while (pcur)
//	{
//		printf("%d -> ", pcur->data);
//		pcur = pcur->next;
//	}
//	printf("NULL\n");
//}

SNode* BuyNode(Datatype x)
{
	SNode* NewNode = (SNode*)malloc(sizeof(SNode));
	if (NewNode == NULL)
	{
		perror("malloc fail");
		exit(1);
	}
	NewNode->data = x;
	NewNode->next = NULL;
	return NewNode;
}

void PushBack(SNode** pphead, Datatype x)
{
	assert(pphead);
	SNode* NewNode = BuyNode(x);
	SNode* pcur = *pphead;

	if (pcur == NULL)
	{
		*pphead = BuyNode(x);
		*pphead = NewNode;
	}
	else
	{
		while (pcur->next)
		{
			pcur = pcur->next;
		}
		pcur->next = NewNode;
	}
}

void PushFront(SNode** pphead, Datatype x)
{
	assert(pphead);
	SNode* NewNode = BuyNode(x);
	NewNode->next = *pphead;
	*pphead = NewNode;
}


void PopBack(SNode** pphead)
{
	assert(pphead && *pphead);

	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SNode* ptail = *pphead;
		SNode* prev = *pphead;
		while (ptail->next)
		{
			prev = ptail;
			ptail = ptail->next;
		}
		free(ptail);
		ptail = NULL;
		prev->next = NULL;
	}
}

void PopFront(SNode** pphead)
{
	assert(pphead && *pphead);
	SNode* next = (*pphead)->next;
	free(*pphead);
	*pphead = next;
}

void SLTInsert(SNode** pphead, SNode* pos, Datatype x)
{
	assert(pphead && *pphead);
	assert(pos);

	SNode* NewNode = BuyNode(x);
	if (pos == *pphead)
	{
		PushFront(pphead, x);
	}
	else
	{
		SNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		NewNode->next = pos;
		prev->next = NewNode;
	}
}

void SLTInsertAfter(SNode* pos, Datatype x)
{
	assert(pos);
	SNode* NewNode = BuyNode(x);

	NewNode->next = pos->next;
	pos->next = NewNode;
}

void Erase(SNode** pphead, SNode* pos)
{
	assert(pphead && *pphead);
	assert(pos);
	if (pos == *pphead)
	{
		PopFront(pphead);
	}
	else {
		SNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		//prev pos pos->next
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SlTErase(SNode* pos)
{
	assert(pos && pos->next);
	SNode* del = pos->next;
	//pos del del->next
	pos->next = del->next;
	free(del);
	del = NULL;
}

void SListDesTory(SNode** pphead)
{
	assert(pphead && *pphead);

	SNode* pcur = *pphead;
	while (pcur)
	{
		SNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	//pcur
	*pphead = NULL;
}